/**
 * <pre>
 * Author:		linriqing
 * Create:	 	2014-6-10 下午04:53:46
 * Copyright: 	Copyright (c) 2014
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.msls.tools;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
 * <pre>
 * Json工具类
 * </pre>
 * @author linriqing
 * @version 1.0, 2014-6-10
 */
public class JsonUtils
{
	public static final String JSON_DATETIME_FORMAT = "yyyyMMddHHmmss";

	public static GsonBuilder createGson()
	{
		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>()
		{
			@Override
			public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
					throws JsonParseException
			{
				try
				{
					SimpleDateFormat sdf = new SimpleDateFormat(JSON_DATETIME_FORMAT);
					return sdf.parse(json.getAsString());
				}
				catch (ParseException e)
				{
					throw new RuntimeException("日期格式不对,Pattern应该为:yyyyMMddHHmmss", e);
				}
			}
		});
		gsonBuilder.registerTypeAdapter(Date.class, new JsonSerializer<Date>()
		{
			@Override
			public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2)
			{
				SimpleDateFormat sdf = new SimpleDateFormat(JSON_DATETIME_FORMAT);
				return new JsonPrimitive(sdf.format(arg0));
			}
		});
		return gsonBuilder;
	}
}
